package com.study.mike.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.mike.common.constants.RedisKey;
import com.study.mike.common.exception.BizException;
import com.study.mike.mapper.FishEquipmentMapper;
import com.study.mike.model.dto.FishEqDTO;
import com.study.mike.model.dto.PageDTO;
import com.study.mike.model.entity.FishEquipmentDO;
import com.study.mike.model.po.FishEqPO;
import com.study.mike.model.po.FishEquipmentPO;
import com.study.mike.service.FishEquipmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author KangHui
 * @Date 2023/6/20 17:06
 */
@Service
@Slf4j
@CacheConfig(cacheNames = RedisKey.ONE_HOUR)
public class FishEquipmentServiceImpl extends ServiceImpl<FishEquipmentMapper, FishEquipmentDO> implements FishEquipmentService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    public Boolean addFishEq(FishEquipmentPO po) {
        FishEquipmentDO equipmentDO = new FishEquipmentDO();
        BeanUtils.copyProperties(po, equipmentDO);
        try {
            return this.save(equipmentDO);
        } catch (DuplicateKeyException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BizException("400", "数据已存在，若有其他操作请执行更新！");
        }

    }

    @Override
    public Boolean setStatus(Long id, Integer status) {
        FishEquipmentDO equipmentDO = new FishEquipmentDO();
        equipmentDO.setId(id);
        equipmentDO.setStatus(status);
        return this.updateById(equipmentDO);
    }

    @Override
    @Cacheable(key = "#root.methodName + #po.pageSize + #po.pageCurrent", unless = "#result==null")
    public PageDTO<FishEqDTO> queryFishEq(FishEqPO po) {
        PageDTO<FishEquipmentDO> pageDTO = new PageDTO<>(po.getPageCurrent(), po.getPageSize());
        LambdaQueryWrapper<FishEquipmentDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(po.getName()), FishEquipmentDO::getName, po.getName())
                .like(StrUtil.isNotBlank(po.getBn()), FishEquipmentDO::getBn, po.getBn())
                .eq(ObjectUtil.isNotNull(po.getStatus()), FishEquipmentDO::getStatus, po.getStatus())
                .eq(ObjectUtil.isNotNull(po.getType()), FishEquipmentDO::getType, po.getType())
                .orderByDesc(FishEquipmentDO::getCreateTime);
        IPage page = this.page(pageDTO, wrapper);
        List<FishEquipmentDO> records = page.getRecords();
        List<FishEqDTO> list = JSONUtil.toList(JSONUtil.toJsonStr(records), FishEqDTO.class);
        pageDTO.setRecords(list);
        PageDTO<FishEqDTO> result = new PageDTO<>(page.getCurrent(), page.getSize(), page.getTotal());
        result.setRecords(list);
        return result;
    }

    @Override
    @CacheEvict(allEntries = true)
    public Boolean deleteFishEq(List<FishEquipmentPO> pos) {
        if (CollectionUtil.isEmpty(pos)) {
            return false;
        }
        List<Long> ids = pos.stream().map(x -> x.getId())
                .collect(Collectors.toList());
        return this.removeByIds(ids);
    }

    @Override
    @CacheEvict(allEntries = true)
    public Boolean updateFishEq(FishEquipmentPO po) {
        FishEquipmentDO fishEquipmentDO = new FishEquipmentDO();
        BeanUtils.copyProperties(po, fishEquipmentDO);
        try {
            return this.updateById(fishEquipmentDO);
        } catch (DuplicateKeyException e) {
            log.error(po.getId() + "数据编辑异常" + e.getMessage());
            return false;
        }
    }
}
